package com.fu.mr.bluetoothdchat.thread;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.util.Log;

import java.io.IOException;
import java.util.UUID;

/**
 * <pre>
 *     author : Mr.Fu
 *     e-mail : 18622268981@163.com
 *     time   : 2020/03/13
 *     desc   : 连接线程,专门用来对外发出连接对方蓝牙的请求,并进行处理
 *              构造函数中通过调用 BluetoothDevice.createRfcommSocketToServiceRecord(),
 *              从带连接的 device 产生 BluetoothSocket,然后在 run() 方法中执行 connect 操作,
 *              成功后调用 BluetoothChatService的connected（）方法，
 *              定义cancel（）在关闭线程时能关闭socket
 *     version: 1.0
 * </pre>
 */

public class ConnectThread extends Thread {

    public static final String TAG = ConnectThread.class.getSimpleName();

    private final BluetoothSocket mSocket;
    private final BluetoothDevice mDevice;
    private BluetoothAdapter mAdapter;
    private ConnectListener mListener;

    // UUID --> 通用唯一识别码
    private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");

    public ConnectThread(BluetoothDevice device) {

        mDevice = device;
        mAdapter = BluetoothAdapter.getDefaultAdapter();
        BluetoothSocket tmp = null;
        // Get a BluetoothSocket to connect with the given BluetoothDevice
        try {
            // MY_UUID is the app's UUID string, also used by the server code
            tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
        } catch (IOException e) {
            e.printStackTrace();
        }
        mSocket = tmp;
    }

    @Override
    public void run() {

        Log.d(TAG, "ConnectThread -> run()");
        mAdapter.cancelDiscovery();
        try {
            mSocket.connect();
        } catch (IOException e) {
            e.printStackTrace();
            // 2020/3/13 连接失败
            if (mListener != null) {
                mListener.onConnectFailed();
            }
            return;
        }
        Log.d(TAG, "主动连接成功!");
        if (mListener != null) {
            mListener.onConnected(mSocket, mDevice);
        }
    }

    public void cancel() {

        Log.w(TAG, "ConnectThread -> cancel()");
        if (mSocket != null) {
            try {
                mSocket.close();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
    }

    public void setConnectListener(ConnectListener listener) {

        mListener = listener;
    }

    public static interface ConnectListener {

        void onConnected(BluetoothSocket socket, BluetoothDevice device);

        void onConnectFailed();
    }
}
